package com.leoman.service.impl;

import com.leoman.core.Constant;
import com.leoman.dao.CityDao;
import com.leoman.dao.ProvinceDao;
import com.leoman.dao.RegionDao;
import com.leoman.entity.City;
import com.leoman.entity.Province;
import com.leoman.service.ProvinceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * ProvinceServiceImpl
 * Created by 涂奕恒 on 2016/10/18 0018 下午 3:23.
 */
@Service
public class ProvinceServiceImpl implements ProvinceService {

    @Autowired
    private ProvinceDao provinceDao;

    @Autowired
    private CityDao cityDao;

    @Autowired
    private RegionDao regionDao;

    @Override
    public List<Province> findAll() {
        return provinceDao.findAll();
    }

    @Override
    public Page<Province> find(int pageNum, int pageSize) {
        return provinceDao.findAll(new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
    }

    @Override
    public Page<Province> find(int pageNum) {
        return find(pageNum, Constant.PAGE_DEF_SIZE);
    }

    @Override
    public Province getById(int id) {
        return provinceDao.findOne(id);
    }

    @Override
    public void deleteById(int id) {
        provinceDao.delete(id);
    }

    @Override
    public Province create(Province province) {
        return provinceDao.save(province);
    }

    @Override
    public Province update(Province province) {
        return provinceDao.save(province);
    }

    @Override
    @Transactional
    public void deleteAll(int[] ids) {
        for (int id : ids) {
            deleteById(id);
        }
    }

    @Override
    public List<Province> findList() {
        List<Province> provinceList = provinceDao.findAll();
        List<City> cityList;

        for (Province province : provinceList) {
            cityList = cityDao.findListByProvinceId(province.getId());

            for (City city : cityList) {
                city.setRegionList(regionDao.findListByCityId(city.getId()));
            }

            province.setCityList(cityList);
        }

        return provinceList;
    }
}